package practice;

import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoFileChooser;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class PhtotFrame extends JFrame {
    private LovoFileChooser lfc;

    private LovoButton  lb;

    public PhtotFrame(){
        this.setResizable(false);
        this.setSize(500, 500);
        this.setDefaultCloseOperation(3);
        this.setLayout(null);

        lfc = new LovoFileChooser(this);
        lfc.setBounds(50, 50, 150, 200);

        lb = new LovoButton("上传", 50, 330, this);

        lb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String filePath = lfc.getFilePath();
                if(filePath == null){
                    JOptionPane.showMessageDialog(null, "请先选择上传的文件");
                }else{
                   // System.out.println(filePath);
                    String regex = "\\.(jpg|gif|png)";
                    if(filePath.substring(filePath.lastIndexOf(".")).matches(regex)){
                        File userFile = new File(filePath);

                        String phtotPath = "E:\\javaooGit\\javaooDay22\\photo";

                        File newFile = new File(phtotPath);

                        if(!newFile.exists()){
                            try {
                                newFile.mkdir();

                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }

                        File photoFile = new File(phtotPath + File.separator+ System.currentTimeMillis() +
                                filePath.substring(filePath.lastIndexOf(".")));

                        try (
                                InputStream in = new FileInputStream(userFile);
                                OutputStream out = new FileOutputStream(photoFile);
                                ){

//                            byte[] b = new byte[1024];
                            int len = 0;

                            while(len != -1){
                                len = in.read();
                                out.write((char)len);
                            }
                            out.flush();
                            JOptionPane.showMessageDialog(null, "上传成功");
                        }catch (Exception e1){
                            e1.printStackTrace();
                        }
                    }else{
                        JOptionPane.showMessageDialog(null, "文件格式错误（必须是.jpg/.gif/.png）");
                    }
                }
            }
        });

        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public static void main(String[] args){
new PhtotFrame();
    }
}
